package org.voovan.korla.socket;

import org.voovan.korla.KorlaStatic;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 周期发送任务对象
 *
 * @author: helyho
 * Korla Framework.
 * WebSite: https://github.com/helyho/Korla
 * Licence: Apache v2 License
 */
public class FlushTask implements Delayed {
    private long id = KorlaStatic.UNIQUE_ID.nextNumber();
    private long delayTime;
    private Runnable task;
    private boolean isAvaliable;

    public FlushTask(long delayTime, Runnable task) {
        this.delayTime = System.currentTimeMillis() + delayTime;
        this.task = task;
        this.isAvaliable = true;
    }

    public long getId() {
        return id;
    }

    public long getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(long delayTime) {
        this.delayTime = delayTime;
    }

    public Runnable getTask() {
        return task;
    }

    public void setTask(Runnable task) {
        this.task = task;
    }

    public boolean isAvaliable() {
        return isAvaliable;
    }

    public void setAvaliable(boolean avaliable) {
        isAvaliable = avaliable;
    }

    public void run() {
        if(isAvaliable) {
            task.run();
        }
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.delayTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed delayed) {
        if (delayed instanceof FlushTask) {
            FlushTask flushTask = (FlushTask) delayed;
            if (this.getDelayTime() > flushTask.getDelayTime()) {
                return 1;
            } else if (this.getDelayTime() == flushTask.getDelayTime()) {
                return 0;
            } else {
                return -1;
            }
        } else {
            return 0;
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof FlushTask)) return false;
        FlushTask flushTask = (FlushTask) o;
        return id == flushTask.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
